from . import api
from .. import db
from .authentication import auth
from ..utils.aliyunVideo import *
from ..utils.checkUpload import *
from ..models import *
from flask import request, jsonify, g, current_app
import traceback, time, random
# 自然语言处理包
import jieba
import jieba.analyse


class JaccardSimilarity(object):
    """
    jaccard相似度
    """
    def __init__(self, content_x1, content_y2):
        self.s1 = content_x1
        self.s2 = content_y2

    @staticmethod
    def extract_keyword(content):  # 提取关键词
        # 切割
        seg = [i for i in jieba.cut(content, cut_all=True) if i != '']
        # 提取关键词
        keywords = jieba.analyse.extract_tags("|".join(seg), topK=200, withWeight=False)
        return keywords

    def main(self):
        # 分词与关键词提取
        keywords_x = self.extract_keyword(self.s1)
        keywords_y = self.extract_keyword(self.s2)

        # jaccard相似度计算
        intersection = len(list(set(keywords_x).intersection(set(keywords_y))))
        union = len(list(set(keywords_x).union(set(keywords_y))))
        # 除零处理
        sim = float(intersection)/union if union != 0 else 0
        return sim


# √
# 实现个性化推荐功能
@api.route('/recommend', methods=['GET'])
def recommend():
    # 首先检查用户是否已经完善信息
    if g.current_user.constellation == '' or g.current_user.hobby == '':
        # 用户并未完善信息
        response= jsonify(
            error='Please update your profile!'
        )
        response.status_code = 404
        return response
    # 选择所有异性用户
    users = User.query.filter_by(gender=abs(g.current_user.gender - 1)).all()
    users = [u.to_json_personal_detail() for u in users]
    current_user_profile = g.current_user.school + g.current_user.grade + g.current_user.constellation + g.current_user.hobby
    followUsers = follows.query.filter_by(fans_id=g.current_user.user_id).all()
    followUsersId = [u.user_id for u in followUsers]

    user_list = []
    for u in users:
        try:
            u_profile = u['school'] + u['grade'] + u['constellation'] + u['hobby']
        except:
            continue
        similarity = JaccardSimilarity(current_user_profile, u_profile)
        u['similarity'] = similarity.main()
        u['isFollow'] = True if u['user_id'] in followUsersId else False
        user_list.append(u)
    
    # 根据相似度从大到小排序
    user_list = sorted(user_list, key=lambda e: e.__getitem__('similarity'), reverse=True)
    response = jsonify(
        message='Get recommend successfully!',
        user_list=user_list,
        count=len(user_list)
    )
    response.status_code = 200
    return response